var global = {
    apiUrl: 'https://jzj.freei.cc',
    community_id: '',
    titleText:'智慧社区后台',
    communityContent: {}
}
//设置统一title
$('title').text(global.titleText);

//ajax封装
function  getAjax(url,callback,data) {
    $.ajax({
        url:url,
        dataType:'json',
        data:data,
        header: {
            'content-type': 'application/json' //默认值
        },
        traditional:true,
        success(res){
            callback(res)
        }
    })
}

function postAjax(url,callback,data) {
    $.ajax({
        url:url,
        dataType:'json',
        type: 'post',
        data:data,
        header: {
            'content-type': 'application/json' //默认值
        },
        traditional:true,
        success(res){
            callback(res)
        }
    })
}

function getAsyncAjax(url,callback,data){
    $.ajax({
        url:url,
        dataType:'json',
        type:'GET',
        data:data,
        async:false,
        header: {
            'content-type': 'application/json' //默认值
        },
        traditional:true,
        success(res){
            callback(res)
        }
    })
}
//接收参数
function GetRequest() {
    var url = location.search; //获取url中"?"符后的字串
    var theRequest = new Object();
    if (url.indexOf("?") != -1) {
        var str = url.substr(1);
        strs = str.split("&");
        for (var i = 0; i < strs.length; i++) {
            theRequest[strs[i].split("=")[0]] = decodeURIComponent(strs[i].split("=")[1]);
        }
    }
    return theRequest;
}

//正则验证
function validation (data,type) {
    let str = ''
    if(type == 'phone')
    {
      str = /^1\d{10}$/
    }
    else if(type == 'idcard')
    {
      str = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/
    }
    else if(type == 'name')
    {
      str = /^[\u4E00-\u9FA5A-Za-z]+$/
    }
    else if(type == 'number')
    {
      // 验证非负浮点数
      str = /^(\-|\+)?\d+(\.\d+)?$/
    }
    else if(type == 'alphanumeric')
    {
      // 验证由数字和26个英文字母组成的字符串
      str = /^[A-Za-z0-9]+$/
    }
    if (str.test(data)) {
      return true
    }
    else{
      return false
    }
}


/*
* 图片上传函数
*/
function imgUpload(selectorInput,selectorImg,callback){
    var fileInput = document.getElementById(selectorInput),
        fileImage = document.getElementById(selectorImg);
    // fileInfo = document.getElementById("fileInfo");
    //监听change事件
    fileInput.addEventListener('change',function(e){
        //清空预览区背景图片
        // console.log(e.target.files);
        // fileImage.style.backgroundImage = '';
        fileImage.innerHTML = '';
        //检查文件是否选择
        if(!fileInput.value){
            fileInfo.innerHTML = "没有选择任何文件";
            return;
        }

        //获取file的引用
        var file = fileInput.files;
        var img = ' ';
        //读取文件
        for(var i=0,file=fileInput.files;i<file.length;i++){
            var reader = new FileReader();
            reader.onload = function(e){
                // console.log(e);
                var data = e.target.result;
                // console.log(e.target)
                // fileImage.style.backgroundImage = 'url('+data+')';
                var img = document.createElement("img");
                img.src=data;
                fileImage.appendChild(img)
            }
            // 以DataURL的形式读取文件:
            reader.readAsDataURL(file[i]);
        }
        upload(fileInput,callback);
    });

}
//多图上传
function imgUploadShow(selectorInput,selectorImg){
    var contentImgInput = document.getElementById(selectorInput);
    let id = contentImgInput.id
    let end =id.charAt(id.length-1)
    var contentImgBox = document.getElementById(selectorImg);
    var imgArr = [];
    contentImgInput.addEventListener('change',function () {
        var file = contentImgInput.files;
        console.log(imgArr);
        for(var i=0,file=contentImgInput.files;i<file.length;i++){
        	imgArr.push(file[i]);
            var reader = new FileReader();
            reader.onload = function(e){
                // console.log(e);
                var data = e.target.result;
                // console.log(e.target)
                var img = `
                     <div class="content-img-item">
                        <img src="${data}" alt="">
                        <div class="cancle themeColor">删 除</div>
                     </div>
                `;
                // headImgBox.appendChild(img)
                $(`#${selectorImg} .new`).append(img);
                if(end == 2){
                    $(`#${selectorInput}`).parent().find('#upload-content-img2').css('display','block')
                }else{
                    $(`#${selectorInput}`).parent().find('#upload-content-img').css('display','block')
                }
               
            }
            // 以DataURL的形式读取文件:
            reader.readAsDataURL(file[i]);
        }

    })
    return imgArr

}

function upload(fileInput,callback){
    for(var i=0;i<fileInput.files.length;i++){
        uploadImg(fileInput.files[i],callback)
    }
}
//多图上传
function allImgUpload(arr,fn){
    console.log(arr);
    if(arr==0){
        alert('请先选择图片再点击上传')
    }else{
        for(var i=0;i<arr.length;i++){
            uploadImg(arr[i],fn);
        }
    }
}
function uploadImg(f,callback) {
    var xhr = new XMLHttpRequest();
    var formData = new FormData();
    // for(var i=0; f=fileInput.files[i]; i++){
    //     formData.append('files', f);
    // }
    formData.append('file',f);
    xhr.onreadystatechange = function (e) {
        if(xhr.readyState == 4){
            if(xhr.status == 200){
                console.log(xhr.responseText);
                // document.getElementById('imgUrl').value = xhr.responseText;
                callback(xhr.responseText)
            }else {
                console.log(xhr.responseText);
            }
        }
    }

    xhr.open('POST', 'https://jzj.freei.cc/admin_upload', true);
    xhr.send(formData);
}


//上传图片
function sendFile(file, editor, $editable){
    var filename = false;
    try{
        filename = file['name'];
    } catch(e){
        filename = false;
    }
    if(!filename){
        $(".note-alarm").remove();
    }
    //以上防止在图片在编辑器内拖拽引发第二次上传导致的提示错误
    data = new FormData();
    data.append("file", file);
    data.append("key",filename); //唯一性参数

    $.ajax({
        data: data,
        type: "POST",
        url: "https://jzj.freei.cc/admin_upload",
        cache: false,
        contentType: false,
        processData: false,
        success: function(url) {
            // console.log(url)
            if(url){
                let img = url
                editor.insertImage($editable, img);
            }
        },
        error:function(){
            alert("上传失败！");
            return;
        }
  });
}

/*图片上传函数  end*/

//转换时间格式 （年月日）
function setTime(timestr){
    var date = new Date(timestr);
    var Y = date.getFullYear();
    var M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1);
    var D = change(date.getDate());
    var h = change(date.getHours());
    var minute = date.getMinutes();
    var second = date.getSeconds();
    minute = minute < 10 ? ('0' + minute) : minute;
    second = second < 10 ? ('0' + second) : second;
    return Y + '-' + M + '-' + D + ' ' + h + ':' + minute + ':' + second;
}
function change(t) {
    if (t < 10) {
        return "0" + t;
    } else {
        return t;
    }
}
function getNow(type){
    let date = new Date();
    let year = date.getFullYear();
    let month = date.getMonth()+1;
    month = month>9?month:'0'+month;
    let day = date.getDate();
    day = day>9?day:'0'+day;
    let h = date.getHours();
    h = h>9?h:'0'+h;
    let m = date.getMinutes();
    m = m>9?m:'0'+m;
    let s = date.getSeconds();
    s= s>9?s:'0'+s;
    if(type == 0){
        //YYYY-MM-DD hh:mm:ss
        return `${year}-${month}-${day} ${h}:${m}:${s}`
    }
    if(type == 1){
        //YYYY-MM-DD
        return `${year}-${month}-${day}`
    }
    if(type == 2){
        //hh:mm:ss
        return `${h}:${m}:${s}`
    }

}
//转换时间格式 （年月日）
function setTime2(timestr){
    var date = new Date(timestr * 1000); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
    var Y = date.getFullYear();
    var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1);
    var D = change(date.getDate());
    var h = change(date.getHours());
    var m = change(date.getMinutes());
    var s = change(date.getSeconds());
    return Y + '-' + M + '-' + D+ ' ' + h + ':' + m + ':' + s;
  }

function setTime3(timestr){
    var date = new Date(timestr);
    var Y = date.getFullYear();
    var M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1);
    var D = change(date.getDate());
    var h = change(date.getHours());
    var minute = date.getMinutes();
    var second = date.getSeconds();
    minute = minute < 10 ? ('0' + minute) : minute;
    second = second < 10 ? ('0' + second) : second;
    return Y + '.' + M + '.' + D ;
}

//日期转为时间戳
function dateTotimestamp(date){
    let timestamp = Math.round(new Date(date)/1000);
    return timestamp;
}

//获取年龄
function jsGetAge(strBirthday)
{
    var returnAge;
    var strBirthdayArr=strBirthday.split("-");
    var birthYear = strBirthdayArr[0];
    var birthMonth = strBirthdayArr[1];
    var birthDay = strBirthdayArr[2];

    d = new Date();
    var nowYear = d.getFullYear();
    var nowMonth = d.getMonth() + 1;
    var nowDay = d.getDate();

    if(nowYear == birthYear)
    {
        returnAge = 0;//同年 则为0岁
    }
    else
    {
        var ageDiff = nowYear - birthYear ; //年之差
        if(ageDiff > 0)
        {
            if(nowMonth == birthMonth)
            {
                var dayDiff = nowDay - birthDay;//日之差
                if(dayDiff < 0)
                {
                    returnAge = ageDiff - 1;
                }
                else
                {
                    returnAge = ageDiff ;
                }
            }
            else
            {
                var monthDiff = nowMonth - birthMonth;//月之差
                if(monthDiff < 0)
                {
                    returnAge = ageDiff - 1;
                }
                else
                {
                    returnAge = ageDiff ;
                }
            }
        }
        else
        {
            returnAge = -1;//返回-1 表示出生日期输入错误 晚于今天
        }
    }

    return returnAge;//返回周岁年龄

}

//日期选择插件调用
function datePicker(id,format,start,callback){
    laydate({
        elem:'#'+id,
        event:'click',
        format:format,//'YYYY-MM-DD hh:mm:ss'
        istime:true,
        istoday:true,
        issure:true,
        min:'2010-01-01 00:00:00',
        max:'2050 23:59:59',
        start:start,
        choose:function(dates){
            callback(dates);
        }
    });
}

//判断是否登陆
var isLogin = sessionStorage.getItem('status');
// console.log(isLogin);
if(isLogin == 1){

}else{
    location.href = 'login.html'
}

//type (0 总后台 1 社区健康商城后台 2社区后台 3社区商城  4 厨房)
//判断是否登陆
var content = sessionStorage.getItem('communityContent');

if(content){
    let communityContent = JSON.parse(content);
    global.communityContent = communityContent;
    global.community_id = communityContent.community_id;
    global.community_type = communityContent.type;
    global.community_service_shop_id = communityContent.community_service_shop_id;
    global.shop_id = communityContent.health_shop_id;
    global.kitchen_id = communityContent.kitchen_id;
}

var mainType = sessionStorage.getItem('mainType');
var communityLevInfo = sessionStorage.getItem('communitylevelInfo');
if(communityLevInfo){
    global.communityLevInfo = communityLevInfo;
}
if(mainType){
    global.mainType = mainType//1为市代 2区代 3无市代的区代
}

var shopUserId = sessionStorage.getItem('shopUserId');

if(shopUserId){
    global.shopUserId = shopUserId
}

// var orderNum = sessionStorage.getItem('orderNum');

// if(orderNum){
//     global.orderNum = orderNum
// }

